using Godot;
using System;
using static InputConst;
namespace Views.Edit
{
    public class EditCanvasInteractive : Control
    {

        [Export]
        private StyleBox _selectStyle;

        private bool _isSelecting;
        private Vector2 _lastPosition;
        private Rect2 _selectRect;
        private EditCanvas _canvas;
        private EditViewport _viewport;
        private EditViewportInteractive _viewportInteractive;
        public EditCanvas EditCanvas
        {
            get
            {
                if (_canvas == null)
                    _canvas = GetParent<EditCanvas>();
                return _canvas;
            }
        }

        public EditViewport EditViewport
        {
            get
            {
                if (_viewport == null)
                    _viewport = EditCanvas.EditViewport;
                return _viewport;
            }
        }

        public EditViewportInteractive ViewportInteractive
        {
            get
            {
                if (_viewportInteractive == null)
                    _viewportInteractive = EditViewport.Interactive;
                return _viewportInteractive;
            }
        }

        public StyleBox SelectStyle
        {
            get
            {
                if (_selectStyle == null)
                    _selectStyle = GetStylebox("SelectBox", "Edit");
                return _selectStyle;
            }
        }

        #region Godot API
        public override void _Ready()
        {

        }
        public override void _Input(InputEvent @event)
        {
            if(_isSelecting && @event is InputEventMouseMotion)
                UpdateSelectRect(GetLocalMousePosition());
        }
        public override void _GuiInput(InputEvent @event)
        {
            if (@event.IsActionPressed(CANVAS_SELECT))
                BeginCanvasSelect(GetLocalMousePosition());
            else if(@event.IsActionReleased(CANVAS_SELECT))
                EndCanvasSelect();
        }

        #endregion


        #region Private Functions
        private void BeginCanvasSelect(Vector2 position)
        {
            _lastPosition = position;
            _selectRect = new Rect2(position, Vector2.Zero);
            _isSelecting = true;
            Debug.Log("BeginCanvasSelect");
        }
        private void EndCanvasSelect()
        {
            Debug.Log("EndCanvasSelect");
            _isSelecting = false;
            ViewportInteractive.UpdateSelect(_isSelecting, _selectRect);
            EditCanvas.ApplySelect(_selectRect);
        }
        private void UpdateSelectRect(Vector2 position)
        {
            _selectRect = RectUtil.FromLTRB(_lastPosition, position);
            ViewportInteractive.UpdateSelect(_isSelecting, _selectRect);
        }

        #endregion

    }
}